//login.js
const API = require("../../utils/api")
let app = getApp();
Page({
    data: {
        loading:true,
        currentIndex: 0
    },
    onLoad: function () {
        let currentPage = getCurrentPages();
        let currentPageName = currentPage[currentPage.length - 1].route;
        console.log("当前页面为注册页面: ", currentPageName == "pages/registe/registe")
        wx.hideHomeButton();
        var self = this;
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: function (res) {
                            console.log(res)
                            wx.setStorageSync('userInfo', res.userInfo);
                            self.login();
                        }
                    })

                } else {
                    self.setData({
                        loading:false
                    })
                    console.log("用户未授权获取个人信息");
                }
            }
        });
    },
    bindGetUserInfo: function (e) {
        let self = app;
        //将获取的信息传到后端
        console.log(e);
        if (typeof e.detail.userInfo == "undefined") {
            console.log("用户拒绝授权");
            wx.showToast({ title: '授权登录失败!请允许授权', icon: 'none', duration: 2000 });
        }else{
            wx.showLoading({
                title: '授权登录中',
            })
           this.login()
        }
    },
    login: ()=>{
        wx.login({
            success: function (res) {
              var code = res.code;
              if (code) {
                API.login({
                  code: code
                }).then(res=>{
                    
                    wx.hideLoading();
                    wx.setStorageSync('id', res.id);
                    wx.switchTab({url: "../home/index"});
                }).then(error=>{
                    console.log(error)
                })
              } else {
                console.log('获取用户登录态失败！' + res.errMsg)
              }
            }
          });
    }
});